<template>
  <el-drawer v-model="drawerVisible" :destroy-on-close="true" size="1250px" :title="`${drawerProps.title}数据库表`">
    <ProTable
      ref="proTableRef"
      title="代码生成列表"
      row-key="name"
      :indent="30"
      :request-api="loadTableList"
      :columns="columns"
      :pagination="false"
    />
    <template #footer>
      <el-button @click="drawerVisible = false"> 取消</el-button>
      <el-button v-show="!drawerProps.isView" type="primary" @click="handleImportTable"> 导入</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts" name="ImportTable">
import { ref, defineEmits } from "vue";
import { ElMessage } from "element-plus";
import { CodegenTable, createCodegenTable, loadTableList } from "@/api/system/codegenTable";
import { loadDatResourceList } from "@/api/system/dataResource";
import ProTable from "@/components/ProTable/index.vue";
import { ColumnProps } from "@/components/ProTable/interface";
defineOptions({ name: "ImportTable" });
interface DrawerProps {
  row: Partial<CodegenTable.ReqCodegenTable>;
  getTableList?: () => void;
}

const drawerVisible = ref(false);
const proTableRef = ref();
const drawerProps = ref<DrawerProps>({
  row: {}
});

// 接收父组件传过来的参数
const acceptParams = (params: DrawerProps) => {
  drawerProps.value = params;
  drawerVisible.value = true;
};

const handleImportTable = async () => {
  if (!(proTableRef.value.selectedListIds?.length > 0)) {
    ElMessage.error("请选择导入的表");
    return;
  }
  let searchParam = proTableRef.value.searchParam;
  await createCodegenTable({
    dataResourceId: searchParam.dataResourceId as number,
    tableNames: proTableRef.value.selectedListIds
  });
  ElMessage.success("导入成功");
  emit("success");
  drawerVisible.value = false;
};

const columns: ColumnProps[] = [
  { type: "selection", width: 80 },
  {
    prop: "dataResourceId",
    label: "数据源",
    align: "left",
    isShow: false,
    enum: () => loadDatResourceList(),
    fieldNames: { label: "name", value: "id" },
    search: { el: "select", defaultValue: 0 }
  },
  { prop: "name", label: "表名称", align: "left", search: { el: "input" } },
  { prop: "comment", label: "表描述", search: { el: "input" } }
];

const emit = defineEmits(["success"]);
defineExpose({
  acceptParams
});
</script>
